package com.huluobo.a2204parkdemo.news

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.google.gson.Gson
import com.huluobo.base.bean.NewsBean
import com.huluobo.base.bean.NewsBeanItem
import com.huluobo.base.net.ApiService
import com.huluobo.base.net.Const
import dagger.hilt.android.lifecycle.HiltViewModel
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.lang.Exception

/**
 *  Created by LC on 2024/8/28.
 */
class NewsPagingSource(val apiService: ApiService) : PagingSource<Int, NewsBeanItem>() {
    var sum = 0
    override fun getRefreshKey(state: PagingState<Int, NewsBeanItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, NewsBeanItem> {
        return try {
            val page = params.key ?: 1
//            val pageSize = params.loadSize
            val map = mutableMapOf<String, Int>()
            map[Const.PARAM_PAGE] = page
            val json = Gson().toJson(map)
            val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
            val response = apiService.getAllNews(body)
            val items = Gson().fromJson(response.values, NewsBean::class.java)

            sum += items.size
            Log.i("TagA", "newsItems:${sum}")

            val preKey = if (page > 1) page - 1 else null
            val nextKey = if (items.isNotEmpty()) page + 1 else null
            LoadResult.Page(items, preKey, nextKey)
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}